﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using AutoMapper;
using KSUNO_EMS.Models;

namespace KSUNO_EMS.Controllers
{
    public class TestingController : EmsController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListTests()
        {
            var userInfo = MvcApplication.GetCurrentUserInfo();
            var tests = Database.Employees.Include(e => e.ApprovedTests).Single(e => e.Id == userInfo.Id).ApprovedTests
                .ToList()
                .ToDictionary(t => t.Id,
                              t =>
                              new TestResultDTO {Id = t.Id, Name = t.Name});
            var results = 
                Database.EmployeeTestResults.Include(r => r.Question.CorrectAnswer)
                .Where(r=>r.EmployeeId== userInfo.Id)
                .ToList()
                .GroupBy(r => new {r.Question.TestId})
                .Select(
                    g =>
                    new TestResultDTO
                        {
                            Id = g.Key.TestId,
                            Score = String.Format("{0}/{1}", g.Count(q => q.Answer == q.Question.CorrectAnswer), g.Count())
                        })
                .ToList();
            foreach (var result in results)
            {
                TestResultDTO testInfo;
                if (tests.TryGetValue(result.Id, out testInfo))
                    testInfo.Score = result.Score;
            }
            return new ProperJsonResult()
                       {
                           HasDates = true,
                           Data = new AjaxResult(true, tests.Select(t=>t.Value).OrderBy(t=>t.Name))
                       };
        }

        public ActionResult SubmitTest(int testId, string answers)
        {
            var userInfo = MvcApplication.GetCurrentUserInfo();
            var questionsAndAnswers = answers.Deserialise<IEnumerable<QuestionWithAnswerDTO>>();
            
            // Remove results from last attempt
            foreach (var result in Database.EmployeeTestResults.Include(r=>r.Question).Where(r=>r.Question.TestId == testId).ToList())
                Database.EmployeeTestResults.Remove(result);
            Database.SaveChanges();

            // Add results from current attempt
            foreach (var questionWithAnswer in questionsAndAnswers)
                Database.EmployeeTestResults.Add(
                    new EmployeeTestResult()
                        {
                            EmployeeId = userInfo.Id,
                            QuestionId = questionWithAnswer.QuestionId,
                            AnswerId = questionWithAnswer.AnswerId
                        });
            Database.SaveChanges();
            return ListTests();
        }

        public ActionResult TakeTest(int id)
        {
            var userInfo = MvcApplication.GetCurrentUserInfo();
            if (!Database.Employees.Any(e=>e.Id == userInfo.Id && e.ApprovedTests.Any(t=>t.Id == id)))//.SingleOrDefault(a => a.EmployeeId == userInfo.Id && a.TestId == id);
                return new ProperJsonResult() { Data = new AjaxResult(false, "You are not approved to take this test. Contact your manager for approval.") };
            var testResult = new EmployeeTestResult();
            var questionsAndAnswers = Database.TestQuestions.Include(q => q.Answers).Where(q => q.TestId == id).OrderBy(q => q.Number)
                .ToList()
                .Select(q => new
                                 {
                                     q.Id,
                                     q.Number,
                                     q.Text,
                                     Answers = q.Answers.Select(a => new { a.Id, a.Number, a.Text }).OrderBy(a=>a.Number)
                                 });
          //  Database.EmployeeTestApprovals.Remove(approval);

            return new ProperJsonResult()
                       {
                           HasDates = false,
                           Data = new AjaxResult(true, questionsAndAnswers)
                       };
        }

    }
}
